package cn.bitkit.tools.data;


import cn.bitkit.base.util.DateUtil;
import cn.bitkit.base.util.LocalDateTimeUtil;
import cn.bitkit.base.util.RandomUtil;
import cn.bitkit.base.util.StringUtil;

import java.time.LocalDateTime;
import java.util.regex.Pattern;

/**
 * 身份证验证
 * @author changbo
 *
 */
public class IdCardUtil {
	public static final int[] P = new int[]{7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2,1};
	public static final String[] CHECK = new String[]{"1","0","X","9","8","7","6","5","4","3","2"};
	public static final Pattern ID_FORMAT = Pattern.compile("^[1-9][0-9]{16}[0-9Xx]$");
	public static final int MIN_YEAR = 1900;
	public static final int MAX_YEAR = 2100;
	
	public static boolean check(String id){
    	if(id == null || !ID_FORMAT.matcher(id).matches()){
    		return false;
    	}
    	String birthday = id.substring(6, 14);
		LocalDateTime dateTime = LocalDateTimeUtil.parseDateNum(birthday);
		if(dateTime == null || dateTime.getYear() < MIN_YEAR || dateTime.getYear() > MAX_YEAR) {
			return false;
		}
    	String check = genCheckValue(id);
		if(check == null){
			return false;
		}
        return id.toUpperCase().endsWith(check);
    }
    
    /**
     * 1男0女
     */
	public static int getGender(String id){
		if(StringUtil.isEmpty(id) || id.length() <= 17){
			return -1;
		}
		char c = id.charAt(16);
        return (c - '0')%2;
	}
    
    public static String getBirthday(String id){
    	if(StringUtil.isEmpty(id) || id.length() <= 14){
    		return null;
    	}
		return id.substring(6, 14);
    }
    
    public static int getAge(String id){
    	String birthday = getBirthday(id);
    	int y = StringUtil.toInt(birthday);
		if(y == 0){
			return -1;
		}
    	int c = StringUtil.toInt(DateUtil.getCurrentDateNum().substring(0, 4));
    	return c-y;
    }
    
    public static String getAreaCode(String id){
    	String code = null;
    	if(StringUtil.hasValue(id) && id.length() > 6){
    		code = id.substring(0, 6);
    	}
    	return code;
    }
    
    public static String genCheckValue(String data){
    	if(StringUtil.isEmpty(data) || data.length() < 17){
    		return null;
    	}
    	String check = "";
    	if(data.length() > 17){
    		data = data.substring(0, 17);
    	}
    	int t = 0;
    	for(int k=0; k<17; k++){
    		int n = data.charAt(k)-48;
    		t += n*P[k];
    	}
    	t = t%11;
    	check = CHECK[t];
    	return check;
    }
	
	public static String createId(String year){
		String dd = DateUtil.getCurrentDateNum().substring(4, 8);
		String ss = "110112"+year+dd;
		int i = RandomUtil.random(100, 900);
		String id = ss + i;
    	id = id + genCheckValue(id);
    	return id;
	}
	
}
